package com.wwm.springcloud.userservice.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 所有的控制器需要继承此类
 * 实现异常统一处理，相关方法
 */
public class BaseController
{
    private static final String X_REQUESTED_WITH = "X-Requested-With";

    private static final String XML_HTTP_REQUEST = "XMLHttpRequest";

    public static final String JSON_CONTENT_TYPE = "application/json;charset=UTF-8";

    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    /**
     * 统一返回方法
     *
     * @param response
     * @param rtnStr
     * @throws IOException
     */
    public static void out(HttpServletResponse response, Object rtnStr) throws IOException {
        response.setContentType("text/plain;charset=utf-8");//编码格式为utf-8
        logger.info("response=" + rtnStr);
        response.getWriter().write(rtnStr.toString());
    }

    public static void ValidResult(BindingResult bindingResult, String requestId) throws Exception {
        if (bindingResult.hasErrors()) {
            throw new Exception(requestId + "&" + bindingResult.getFieldError().getDefaultMessage());
        }
    }
}
